from __future__ import annotations
from typing import List, Optional
from pydantic import BaseModel, Field


class AttributeGroupBase(BaseModel):
    """
    属性分组表基础字段，用于入参校验
    """
    attr_group_name: str = Field(..., description="分组名称")
    sort: Optional[int] = Field(None, description="分类排序权重(值越小越靠前)")
    descript: Optional[int] = Field(None, description="描述")
    image_id: Optional[int] = Field(None, description="组图片ID")
    category_id: Optional[int] = Field(None, description="分类ID")


class AttributeGroupBo(AttributeGroupBase):
    """新增or修改"""
    attr_group_id: Optional[int] = Field(None, description="分组id")
    pass


class AttributeGroupVo(AttributeGroupBase):
    """返回给前端的模型"""
    attr_group_id: int = Field(..., description="分组主键")

    class Config:
        from_attributes = True


class AttributeBase(BaseModel):
    """
    属性表基础模型，用于新增/修改时的入参校验
    """
    attr_name: str = Field(..., max_length=20, description="属性名称")
    image_id: Optional[int] = Field(None, ge=0, description="组图片ID")
    value_select: Optional[str] = Field(None, max_length=512, description="可选值列表，逗号拼接")
    attr_type: int = Field(..., ge=0, le=1, description="属性类型：0-销售 1-基本")
    enable: int = Field(1, ge=0, le=1, description="启用状态：0-禁用 1-启用")
    category_id: Optional[int] = Field(None, ge=0, description="分类ID")

    @classmethod
    def _normalize_value_select(cls, v):
        """去掉首尾空格，空串自动转 None"""
        if isinstance(v, str):
            v = v.strip()
        return v or None


class AttributeBo(AttributeBase):
    """新增or属性"""
    attr_id: int = Field(None, description="属性主键")
    attr_group_id: int = Field(..., description="分组主键")


class AttributeVo(AttributeBase):
    """返回给前端的模型"""
    attr_id: int = Field(..., description="属性主键")
    attr_group_id: int = Field(..., description="分组主键")

    @property
    def value_list(self) -> List[str]:
        if not self.value_select:
            return []
        return [v.strip() for v in self.value_select.split(",") if v.strip()]

    class Config:
        from_attributes = True
        json_encoders = {
        }
